class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int closestSum = 1e7;
        for (int i = 0; i < nums.size(); i++) {
            int l = i + 1, r = nums.size() - 1;
            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (abs(closestSum - target) > abs(sum - target)) {
                    closestSum = sum;
                }
                if (sum > target) r--;
                else if (sum == target) return target;
                else l++;
            }
        }
        return closestSum;
    }
};
